package com.example.photography.Activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.devilist.recyclerwheelpicker.SingleWheelPicker;
import com.devilist.recyclerwheelpicker.dialog.WheelPicker;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.example.photography.Activity.order.Order_Details;
import com.example.photography.R;
import com.example.photography.adapter.PhotoPublishAdapter;
import com.example.photography.bean.JsonBean;
import com.example.photography.common.BaseActivity;
import com.example.photography.util.OnRecyclerItemClickListener;
import com.example.photography.util.Util;
import com.example.photography.util.WXTouchHelper;
import com.example.photography.view.Message_Dialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.swipebacklayout.BGAKeyboardUtil;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;
import static com.example.photography.util.Util.getJson;

/**
 * 预约页面
 */
public class Appointment_Actvity extends BaseActivity {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_affirm)
    TextView tvAffirm;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.et_demand)
    EditText etDemand;
    @BindView(R.id.ll_item1)
    LinearLayout llItem1;
    @BindView(R.id.tv_site)
    TextView tvSite;
    @BindView(R.id.ll_site)
    LinearLayout llSite;
    @BindView(R.id.et_local)
    EditText etLocal;
    @BindView(R.id.ll_local)
    LinearLayout llLocal;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.ll_date)
    LinearLayout llDate;
    @BindView(R.id.et_price)
    EditText etPrice;
    @BindView(R.id.ll_price)
    LinearLayout llPrice;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.ll_phone)
    LinearLayout llPhone;
    @BindView(R.id.tv_charge)
    TextView tvCharge;
    @BindView(R.id.et_charge)
    EditText etCharge;
    @BindView(R.id.tv_yuan)
    TextView tvYuan;
    @BindView(R.id.rl_charge)
    RelativeLayout rlCharge;
    @BindView(R.id.ll_item2)
    LinearLayout llItem2;
    @BindView(R.id.rc_photo)
    RecyclerView rcPhoto;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    private List<String> imgSelected = new ArrayList<>();
    private PhotoPublishAdapter photoPublishAdapter;
    private ArrayList<JsonBean> options1Items = new ArrayList<>(); //省
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//市
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();//区
    private Message_Dialog mMyDialog;
    private ItemTouchHelper itemTouchHelper;
    Boolean sign_site = false, sign_date = false;
    private static final int REQUEST_CODE = 0x00000011;
    //选择器监听
    private WheelPicker.OnPickerListener pickerListener = new WheelPicker.OnPickerListener() {
        @Override
        public void onPickResult(String tag, String... result) {
            switch (tag) {
                case "single":
                    tvCharge.setText(result[0]);
                    break;

            }
        }
    };

    @Override
    protected void initData() {
        setPermission();
        initJsonData();
        initView();
        initListen();
    }

    private void setPermission() {
        int hasWriteExternalPermission = ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteExternalPermission == PackageManager.PERMISSION_GRANTED) {
            //预加载手机图片。加载图片前，请确保app有读取储存卡权限
            ImageSelector.preload(this);
        } else {
            //没有权限，申请权限。
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x00000012);
        }

    }

    private void initListen() {
        llDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TimePickerView pvTime = new TimePickerBuilder(Appointment_Actvity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        tvDate.setText(formatter.format(date));
                        sign_date = true;
                    }
                }).build();
                pvTime.show();
            }
        });
        llSite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OptionsPickerView pvOptions = new OptionsPickerBuilder(Appointment_Actvity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        tvSite.setText(options1Items.get(options1).getPickerViewText() + "  "
                                + options2Items.get(options1).get(options2) + "  "
                                + options3Items.get(options1).get(options2).get(options3));
                        sign_site = true;
                    }
                })
                        .setTitleText("选择地区")
                        .setDividerColor(Color.parseColor("#E6E6E6"))
                        .setCancelColor(Color.parseColor("#9E9E9E"))
                        .setSubmitColor(Color.parseColor("#FFEE58"))
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(20)
                        .setSelectOptions(18, 13)//默认选中广东茂名
                        .isRestoreItem(false)
                        .build();
                pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
                pvOptions.show();

            }
        });
        tvCharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SingleWheelPicker.instance()
                        .setGravity(Gravity.BOTTOM)
                        .setDefPosition(0)
                        .showAllItem(true)
                        .setResource(R.raw.charge_mode)
                        .setTitle("费用模式")
                        .setPickerListener(pickerListener)
                        .build()
                        .show(getSupportFragmentManager(), "single");
            }
        });
        //确认
        tvAffirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (sign_date && sign_site && !isEmpty(etPrice) && !isEmpty(etDemand) && !isEmpty(etPhone) && !isEmpty(etLocal)) {
                    try {
                        sendOKHttp();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    String date = (String) tvDate.getText();
                    List<String> data = new ArrayList<>();
                    data.add(String.valueOf(etDemand.getText()));
                    data.add((String) tvSite.getText());
                    data.add(String.valueOf(etLocal.getText()));
                    data.add((String) tvDate.getText());
                    data.add(String.valueOf(etPrice.getText()));
                    data.add(String.valueOf(etPhone.getText()));
                    data.add((String) tvCharge.getText());
                    data.add(String.valueOf(etCharge.getText()));
                    if (!isEmpty(etCharge)) {
                        data.add(String.valueOf(etCharge.getText()));
                    }
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList("data", (ArrayList<String>) data);
                    bundle.putStringArrayList("photos", (ArrayList<String>) imgSelected);
                    goToActivity(Order_Details.class, bundle);
                    removeCurrentActivity();
                } else {
                    Util.showToast(Appointment_Actvity.this, "请完善信息~");
                }
            }
        });

        /**
         * 如果没有scrollView包裹 则不用传入scrollView
         */
        WXTouchHelper myCallBack = new WXTouchHelper(photoPublishAdapter, imgSelected, scrollView, 1042);
        itemTouchHelper = new ItemTouchHelper(myCallBack);
        itemTouchHelper.attachToRecyclerView(rcPhoto);
        rcPhoto.setAdapter(photoPublishAdapter);
        photoPublishAdapter.setData(imgSelected);
        rcPhoto.addOnItemTouchListener(new OnRecyclerItemClickListener(rcPhoto) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder) {//单击
                if (viewHolder.getAdapterPosition() == imgSelected.size()) {//点击添加图片
                    addimage();
                } else {//点击已添加的图片
                    long itemId = viewHolder.getAdapterPosition();
                    setImage(imgSelected.get((int) itemId));
                    Util.showToast(Appointment_Actvity.this, String.valueOf(itemId));

                }
            }

            //长按事件中开启拖拽 需要判断position不是+号图片
            @Override
            public void onLongClick(RecyclerView.ViewHolder viewHolder) {//长按
                if (viewHolder.getAdapterPosition() != imgSelected.size()) {
                    BGAKeyboardUtil.closeKeyboard(Appointment_Actvity.this);
                    itemTouchHelper.startDrag(viewHolder);
                }
            }

            @Override
            public void onOtherClick(MotionEvent e) {//空白区域监听

            }
        });

        myCallBack.setDragListener(new WXTouchHelper.DragListener() {
            @Override
            public void deleteState(boolean delete) {
                if (delete) {
                    tvDelete.setAlpha(0.8f);
                    tvDelete.setText("松手即可删除");
                } else {
                    tvDelete.setAlpha(0.5f);
                    tvDelete.setText("拖到此处删除");
                }
            }

            @Override
            public void dragState(boolean start) {
                if (start) {
                    tvDelete.setVisibility(View.VISIBLE);
                } else {
                    tvDelete.setVisibility(View.GONE);
                }
            }

            @Override
            public void clearView() {
                fixBottom();
            }

            @Override
            public void deleteOk() {

            }
        });

    }

    private void sendOKHttp() throws FileNotFoundException {
        //参数类型
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        //创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (imgSelected.size() > 0) {
            for (int i = 0; i < imgSelected.size(); i++) {
                //bitmap转uri
                Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(imgSelected.get(i)));
                //压缩图片
                File file = Util.compressImage(bitmap);
//                File file = uri2File((Uri.parse(mlist.get(i))));
                if (file != null) {
                    builder.addFormDataPart("image_file", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
                }
            }
        }
    }

    private void initView() {
        photoPublishAdapter = new PhotoPublishAdapter(rcPhoto, 9);
        rcPhoto.setAdapter(photoPublishAdapter);
        fixBottom();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_appointment;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private void initJsonData() {//解析数据 （省市区三级联动）
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */

        String JsonData = getJson(this, "province.json");//获取assets目录下的json文件数据
        List<JsonBean> jsonBean = JSONObject.parseArray(JsonData, JsonBean.class);

//        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = (ArrayList<JsonBean>) jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三级）
            List<JsonBean.CityBean> cityList = jsonBean.get(i).getCity();
            for (int c = 0; c < jsonBean.get(i).getCity().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCity().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCity().get(c).getArea() == null
                        || jsonBean.get(i).getCity().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCity().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    private void setImage(String url) {//展开图片//todo 单击图片消失,手势放大缩小功能待实现
        View view = getLayoutInflater().inflate(R.layout.full_image, null);
        ImageView imageView = view.findViewById(R.id.image);//获取diolog里面的返回键和确定键
        //加载网络图片
        Glide.with(this)
                .load(url)
                .transition(withCrossFade()) //Glide提供淡如淡出
                .into(imageView);
        mMyDialog = new Message_Dialog(this, 0, 0, view, R.style.DialogTheme);
//        让自定义dialog的宽度充满整个屏幕
        WindowManager windowManager = this.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = mMyDialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        mMyDialog.getWindow().setAttributes(lp);
        mMyDialog.show();
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMyDialog.dismiss();
            }
        });
    }

    //判断 EditText 是否为空
    private Boolean isEmpty(EditText editText) {
        if ((TextUtils.isEmpty(editText.getText())) && (TextUtils.isEmpty(editText.getText()))) {
            return true;
        } else {
            return false;
        }
    }

    private void addimage() {
        ImageSelector.builder()
                .useCamera(true) // 设置是否使用拍照
                .setSingle(false)  //设置是否单选
                .setMaxSelectCount(9) // 图片的最大选择数量，小于等于0时，不限数量。
                .setSelected((ArrayList<String>) imgSelected) // 把已选的图片传入默认选中。
                .canPreview(true) //是否可以预览图片，默认为true
                .start(this, REQUEST_CODE); // 打开相册
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            imgSelected.clear();
            imgSelected.addAll(Objects.requireNonNull(data.getStringArrayListExtra(ImageSelector.SELECT_RESULT)));
            boolean isCameraImage = data.getBooleanExtra(ImageSelector.IS_CAMERA_IMAGE, false);
//            Log.d("ImageSelector", "是否是拍照图片：" + isCameraImage);
            photoPublishAdapter.setData(imgSelected);
            fixBottom();
        }
    }

    /**
     * 处理recyclerView下面的布局
     * 添加删除时，处理下面布局比上面变化快的问题
     */
    private void fixBottom() {

        int row = photoPublishAdapter.getItemCount() / 3;
        row = (0 == photoPublishAdapter.getItemCount() % 3) ? row : row + 1;//少于3为1行
        row = (4 == row) ? 3 : row;//最多为三行

        int width = Util.getScreenWidth(this);
        int itemWidth = (int) (width - getResources().getDimension(R.dimen.dimen_60)) / 3;//item宽高
        int itemSpace = (int) getResources().getDimension(R.dimen.dimen_10);//item间隔
        int marginTop = (itemWidth * row
                + itemSpace * (row - 1)
                + getResources().getDimensionPixelSize(R.dimen.bottom_margin_top));


        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) llItem2.getLayoutParams();
        params.setMargins(0, marginTop, 0, 0);
        llItem2.setLayoutParams(params);
    }


}
